/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"io/ioutil"
	"os"
)

type Writer struct {
	Id    int
	Name  string
	Value string
}

type Reader struct {
	Name  string
	Value string
}

func writeToFile(filename string, data interface{}) bool {
	if len(filename) < 1 {
		fmt.Println("writeToFile filename invalid")
		return false
	}

	var w bytes.Buffer

	enc := gob.NewEncoder(&w)
	if err := enc.Encode(data); err != nil {
		fmt.Printf("Encode data error: %v\n", err)
		return false
	}

	if fp, err := os.Create(filename); err != nil {
		fmt.Printf("Open '%s' error: %v\n", filename, err)
		return false
	} else {
		defer fp.Close()
		fp.WriteString(w.String())
		fp.Sync()
	}

	return true
}

func readFromFile(filename string, data interface{}) {
	if len(filename) < 1 || data == nil {
		fmt.Println("readFromFile args invalid")
		return
	}

	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Printf("ReadFile '%s' error: %v\n", filename, err)
		return
	}

	r := bytes.NewBuffer(contents)
	dec := gob.NewDecoder(r)

	if err := dec.Decode(data); err != nil {
		fmt.Printf("Decode error: %v\n", err)
		return
	}

	return
}

func main() {
	wData := Writer{0, "firefox", "Web Broswer"}

	writeToFile("/tmp/w", &wData)

	rData := Reader{}
	readFromFile("/tmp/w", &rData)
	fmt.Printf("%v\n", rData)

	w := map[string]string{
		"sublime-text": "Sublime Text",
		"firefox":      "Web Broswer",
		"terminator":   "Terminator",
	}
	writeToFile("/tmp/map", &w)
	r := make(map[string]string)
	readFromFile("/tmp/map", &r)
	fmt.Printf("%v\n", r)
}
